<template>
  <div>
    <!-- 搜索 -->
    <div :class="[$style.search_box, $style.topSelect]">
      <div :class="$style.selectBox">
        <label>运营商：</label>
        <el-select
          style="width:160px"
          v-model="searchs.api"
          clearable
          @change="getRate"
          placeholder="请选择"
        >
        <el-option label="全部" value=""></el-option>
          <el-option v-for="item in company" :key="item.id" :label="item.name" :value="item.id"></el-option>
          
        </el-select>
       </div>
      <SearchInput
        placeholder="订单编号"
        label="订单编号"
        style="margin-right:20px"
        :value="searchs.oid"
        :onChange="(val) => changeSearch('oid',val)"
        :onBlur="getRate"
      />
      <SearchInput
        placeholder="第三方订单号"
        label="请输入"
        style="margin-right:20px"
        :value="searchs.thirdOid"
        :onChange="(val) => changeSearch('thirdOid',val)"
        :onBlur="getRate"
      />
      <SearchInput
        placeholder="电枪编号"
        label="请输入"
        style="margin-right:20px"
        :value="searchs.gunSn"
        :onChange="(val) => changeSearch('gunSn',val)"
        :onBlur="getRate"
      />
      <div :class="$style.selectBox">
        <label>订单状态：</label>
        <el-select
          style="width:160px"
          v-model="searchs.state"
          clearable
          @change="getRate"
          placeholder="请选择状态"
        >
          <el-option label="等待处理中" :value="1"></el-option>
          <el-option label="充电中" :value="2"></el-option>
          <el-option label="充电取消" :value="3"></el-option>
          <el-option label="充电完成" :value="4"></el-option>
          <el-option label="充电异常" :value="5"></el-option>
          <el-option label="充电失败" :value="0"></el-option>
        </el-select>
      </div>
       <div :class="$style.selectBox" style="margin-right:20px;display: flex;align-items: center;">
        <label>创建时间：</label>
        <el-date-picker
          v-model="searchs.appointmentTime"
          type="datetimerange"
          @change="timeChange('appointmentTime')"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp"
          :picker-options="pickerOptions"
          style="height:40px"
        ></el-date-picker>
      </div>
      <div :class="$style.selectBox" style="margin-right:20px;display: flex;align-items: center;">
        <label>订单结算时间：</label>
        <el-date-picker
          v-model="searchs.appointmentTimeEnd"
          type="datetimerange"
          @change="timeChange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp"
          :picker-options="pickerOptions"
          style="height:40px"
        ></el-date-picker>
      </div>
      <div :class="$style.selectBox">
            <label>请选择：</label>
            <el-select clearable v-model="searchs.siteId" @change="changeSite('siteId')" placeholder="站点">
              <el-option
                v-for="item in siteList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select clearable v-model="searchs.pileId" @change="changePile('pileId')" placeholder="选择桩">
              <el-option
                v-for="item in pileList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select clearable v-model="searchs.gunId" @change="changeGun('gunId')" placeholder="选择枪">
              <el-option
                v-for="item in gunList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
       </div>
    </div>
     <div :class="$style.exportbox">
      <button type="button" @click="exportData" :class="$style.export">导出数据</button>
    </div>
    <Panel title="互联互通订单">
      <!-- <div slot='ext' :class="$style.examine">
        <div class="adopt" @click="()=>editStore()">新增</div>
    </div> -->
    <TableEncapsulation
      slot="body"
      :tableConfig="tableConfig"
      :tableData="tableData"
    >
    <template slot="operation" slot-scope="operation">
          <el-button
            type="text"
            @click="()=>commentDetail(operation.row.oid)"
          >查看</el-button>
          <el-button
          v-if="operation.row.state==2"
            type="text"
            @click="()=>remove(operation.row.oid)"
          >停止充电</el-button>
        </template>
        <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
    </Panel>
    
  </div>
</template>
<script>
import request from "@/tools/request";
import requestService from "@/tools/requestExport";
import qs from 'qs';
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import { dateFormat } from "@/tools/time";
export default {
  name: "orderThird",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput
  },
  data() {
    return {
      action: this.$baseUrl+'/export/third/order?token='+localStorage.getItem('token'),
      tableData: [],
      company: [],
      operation: true,
      searchs:{
        component: 'thirdOrder',
        thirdOid: '',
        siteId: '',
        pileId: '',
        gunId: '',
        gunSn:'',
        oid:'',
        api:'',
        state:'',
        appointmentTime: [new Date().getTime() - 3600 * 1000 * 24 * 90, new Date().getTime()],
        appointmentTimeEnd:[],
      },
      endTime:'',
      beginTime:'',
      settBeginTime:'',
      settEndTime:'',
      siteList: [],
      pileList: [],
      gunList: [],
      pager: {
        component: 'thirdOrder',
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
    };
  },
  created() {
    this.endTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : ''
    this.beginTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : ''
    this.settBeginTime =  ''
    this.settEndTime =  ''
    this.companyTh()
    this.searchsFnc()
    this.getRate();
    this.iotSite()
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "订单编号",
            type: "text",
            prop: "oid",
            align: "center"
          },
          {
            label: "第三方订单号",
            type: "text",
            prop: "thirdOid",
            align: "center"
          },
          {
            label: "运营商",
            type: "text",
            prop: "nick",
            align: "center"
          },
          {
            label: "枪编号",
            type: "text",
            prop: "gunSn",
            align: "center"
          },
          {
            label: "公司",
            type: "text",
            prop: "nick",
            align: "center"
          },
         {
            label: "车牌号",
            type: "text",
            prop: "plate",
            align: "center"
          },
          {
            label: "手机号",
            type: "text",
            prop: "phone",
            align: "center"
          },
          {
            label: "支付金额",
            type: "text",
            prop: "amount",
            align: "center"
          },
          {
            label: "充电量",
            type: "text",
            prop: "electricity",
            align: "center"
          },
          {
            label: "实收电费",
            type: "text",
            prop: "receivedPowerPrice",
            align: "center"
          },
          {
            label: "实收服务费",
            type: "text",
            prop: "receivedServicePrice",
            align: "center"
          },
          {
            label: "订单状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 0 ? "等待处理中" : val == 1 ? "充电处理中" : val == 2 ? "充电中" : val == 3 ? "充电取消" : val == 4 ? "充电完成": val == 5 ? "充电异常":"充电失败"
          },
          {
            label: "充电进度",
            type: "other",
            prop: "soc",
            align: "center",
            fnc: val => val  ? val+"%" : ''
          },
          {
            label: "结算状态",
            type: "other",
            prop: "settlement",
            align: "center",
            fnc: val => val == 0 ? "未结算" : "已结算"
          },
          {
            label: "错误信息",
            type: "text",
            prop: "errorMsg",
            align: "center"
          }, 
          {
            label: '订单回调状态',
            type: 'other',
            prop: 'notify',
            align: 'center',
            fnc: val => val == 0 ? '未结束' : val == 1 ? '等待推送' : val == 2 ? '推送成功' : '推送失败'
          },
          {
            label: '回调失败次数',
            type: 'text',
            prop: 'notifyNum',
            align: 'center'
          },
          {
            label: '回调时间',
            type: 'text',
            prop: 'notifyTime',
            align: 'center'
          },
          {
            label: '回调失败信息',
            type: 'text',
            prop: 'notifyMsg',
            align: 'center'
          },
          {
            label: "创建时间",
            type: "text",
            prop: "createTime",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    searchsFnc (){
      let searchs = this.$store.getters.searchs
      if(searchs &&searchs.component == 'thirdOrder'){
        this.searchs = searchs
      }
      let pager = this.$store.getters.pager
      if(pager &&pager.component == 'thirdOrder'){
        this.pager = pager
      }
    },
    async getRate() {
      let endTime = this.endTime
      let beginTime = this.beginTime
      let settBeginTime = this.settBeginTime
      let settEndTime = this.settEndTime
      let state =  this.searchs.state
      let oid = this.searchs.oid, thirdOid = this.searchs.thirdOid
      let gunId = '', siteId = '', pileId = '', api = this.searchs.api
      let gunSn = this.searchs.gunSn
      if(this.searchs.gunId){
        gunId = this.searchs.gunId
      }else{
        if(this.searchs.pileId){
          pileId = this.searchs.pileId
        }else {
          siteId = this.searchs.siteId
        }
      }
      
      if(oid || thirdOid){
        endTime = ''
        beginTime = ''
      }
      let page = this.pager.current
      let search = objectFilter({beginTime, endTime, state, oid, page, thirdOid, gunId, pileId, siteId, gunSn, settBeginTime, settEndTime, api})
      const res = await request({
        url: "/order/third/list",
        method: "POST",
        data: search
      });
      this.tableData = res.page.list
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    async exportData(){
      let endTime = this.endTime
      let beginTime = this.beginTime
      let settBeginTime = this.settBeginTime
      let settEndTime = this.settEndTime
      let state =  this.searchs.state
      let settlement = this.searchs.settlement
       let gunId = '', siteId = '', pileId = ''
      if(this.searchs.gunId){
        gunId = this.searchs.gunId
      }else{
        if(this.searchs.pileId){
          pileId = this.searchs.pileId
        }else {
          siteId = this.searchs.siteId
        }
      }
      let search = objectFilter({beginTime, endTime, state, gunId, siteId, pileId, settlement, settEndTime, settBeginTime })
      await requestService({
        url: "/export/third/order",
        method: "POST",
        responseType: 'blob',
        data: qs.stringify(search)
      });
    },
    
    async changeSite(val){
      let url = '/iot/pile/select'
      let datas = {siteId:this.searchs.siteId}
      const res = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
      this.searchs.gunId = ''
      this.searchs.pileId = ''
      this.pileList = res.list
      this.getRate()
    },
    async changePile(){
      let url = '/iot/pile/gun/all'
      let datas = {pile:this.searchs.pileId}
      const res = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
      this.searchs.gunId = ''
      this.gunList = res.list
      this.getRate()
    },
    changeGun(){
      this.getRate()
    },
    pageChange(val) {
      this.pager.current = val;
      this.getRate();
    },
    //第三方公司
    async companyTh(){
      let { list } = await request({
      url: "/third/company/select",
      method: "POST",
      data: {}
      });
      this.company = list
    },
    timeChange(val){
      if(val == 'appointmentTime'){
        this.endTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : ''
        this.beginTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : ''
      }else{
        this.settBeginTime = this.searchs.appointmentTimeEnd ? (dateFormat(this.searchs.appointmentTimeEnd[0],"yyyy-MM-dd HH:mm:ss")) : ''
        this.settEndTime = this.searchs.appointmentTimeEnd ? (dateFormat(this.searchs.appointmentTimeEnd[1],"yyyy-MM-dd HH:mm:ss")) : ''
      }
      this.getRate()
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    commentDetail(id){
      this.$store.commit('saveSearchs', this.searchs)
      this.$store.commit('savePager', this.pager)
      this.$router.push({ path: "/order/third/info",query:{id:id, type: 'third'} })
    },
    remove(id){
       this.$confirm('确认停充吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
       const del = await request({
                      url:'/order/control/stop/'+id,
                      method: "GET",
                    })
        if(del.code !==0) return
        this.$message.success('停充成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getRate()
      })
    },
    //站点
    async iotSite(){
      let { list } = await request({
      url: "/iot/site/select",
      method: "POST",
      data: {}
      });
       this.siteList = list
    },
  }
}
</script>
<style lang='scss' module>
.exportbox {
    display: flex;
    justify-content: flex-end;
    background: #fff;
    padding-bottom: 5px;
    margin-bottom: 10px;
    .export {
    color: #FFF;
    background-color: #F56C6C;
    border-color: #F56C6C;
    border: 1px solid #F56C6C;
    border-radius: 5px;
    padding: 10px;
    margin-right: 20px;
}
}
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  // margin-bottom: 20px;
}
</style>